#include "UdpClient.hpp"
#include "Log.hpp"
#include <sys/types.h>
#include <sys/socket.h>
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <netinet/in.h>
#include <memory>
#include <netinet/in.h>
#include <arpa/inet.h>
using namespace LogModule;;
//  ./client_udp ip port
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        std::cerr << "Usage" << argv[0] << "clientip clientport" << "\n";
        exit(USAGE_ERR);;
    }
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        LOG(LogLevel::FATAL) << "socket 失败";
        exit(SOCKET_ERR);
    }
    // 填出服务器信息
    struct sockaddr_in server;
    memset(&server, 0, sizeof server);
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = inet_addr(serverip.c_str());
    server.sin_port = htons(serverport);
    while (true)
    {
        std::cout << "please Enter#";
        std::string message;
        std::getline(std::cin, message);
        // 客户端也要bind，但是不用显式调用bind，客户端首次sendto，OS自动bind
        ssize_t n = sendto(sockfd, message.c_str(), message.size(), 0, CONV(&server), sizeof server);
        if (n < 0)
        {
            LOG(LogLevel::ERROR) << "Client sendto fail";
            exit(4);
        }
        char buff[1024];
        struct sockaddr_in peer;
        socklen_t len = sizeof peer;
        n = recvfrom(sockfd, buff, sizeof(buff) - 1, 0, CONV(&peer), &len);
        if (n > 0)
        {
            buff[n] = 0;
            std::cout << "Server say@" << buff << "\n";;
        }
    }
}